package com.mvp.lt.airlineview;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.amap.api.services.core.LatLonPoint;
import com.android.view.IOSDialog;
import com.android.view.IOSDialogUtils;
import com.mvp.lt.airlineview.activity.MainClickActivity;
import com.mvp.lt.airlineview.agorartc.VideoChatViewActivity;
import com.mvp.lt.airlineview.data.constant.LC;
import com.mvp.lt.airlineview.TaskTest.TaskTestActivity;
import com.mvp.lt.airlineview.base.BaseActivity;
import com.mvp.lt.airlineview.event.AppUpdateEvent;
import com.mvp.lt.airlineview.activity.CCBActivity;
import com.mvp.lt.airlineview.activity.CircleActivity;
import com.mvp.lt.airlineview.gismap.GisMapActivity;
import com.mvp.lt.airlineview.kml.MapKmlActivity;
import com.mvp.lt.airlineview.activity.PhotoEditorActivity;
import com.mvp.lt.airlineview.activity.TestStatusBarActivity;
import com.mvp.lt.airlineview.activity.TextCustomKnifeActivity;
import com.mvp.lt.airlineview.activity.TextViewActivity;
import com.mvp.lt.airlineview.location.ADRegionalPromotionActivity;
import com.mvp.lt.airlineview.activity.PlayMediaActivity;
import com.mvp.lt.airlineview.loopview.LoopViewActivity;
import com.mvp.lt.airlineview.map.PolygonLineActivity;
import com.mvp.lt.airlineview.panorama.PanoramaActivity;
import com.mvp.lt.airlineview.picture.PictureInSampleActivity;
import com.mvp.lt.airlineview.record.RecordServiceActivity;
import com.mvp.lt.airlineview.showpicture.ShowPictureActivity;
import com.mvp.lt.airlineview.utils.LocationAmpUtils;
import com.mvp.lt.airlineview.utils.LogUtil;
import com.mvp.lt.airlineview.utils.SPManager;
import com.mvp.lt.airlineview.utils.TTs.TextToSpeechUtils;
import com.mvp.lt.airlineview.utils.ThreadUtil;
import com.mvp.lt.airlineview.utils.UIUtils;
import com.mvp.lt.airlineview.sendtion.xrichtextdemo.ui.MainXRichActivity;
import com.mvp.lt.airlineview.shp.SHPFileActivity;
import com.mvp.lt.airlineview.wayline.WayLineActivity;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.beta.UpgradeInfo;

import com.mvp.lt.airlineview.utils.EncryptUtils;
import com.mvp.lt.airlineview.utils.FileUtils;
import com.mvp.lt.airlineview.utils.TextUtil;
import com.mvp.lt.airlineview.utils.ToastUtils;
import com.mvp.lt.airlineview.activity.MainPictureActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import com.mvp.lt.airlineview.activity.CustViewActivity;
import com.mvp.lt.airlineview.activity.MapMainActivity;

import io.reactivex.functions.Consumer;


/**
 * $activityName
 * 主页
 *
 * @author LiuTao
 * @date 2018/8/6/006
 */


public class HomeActivity extends BaseActivity {
    @BindView(R.id.btn_1)
    Button mBtn1;
    @BindView(R.id.btn_2)
    Button mBtn2;
    @BindView(R.id.btn_3)
    Button mBtn3;
    @BindView(R.id.btn_4)
    Button mBtn4;
    @BindView(R.id.btn_5)
    Button mBtn5;
    @BindView(R.id.btn_9)
    Button btn_9;
    @BindView(R.id.custom_knife)
    Button customKnife;
    @BindView(R.id.btnLoadUpdateInfo)
    Button btnLoadUpdateInfo;
    @BindView(R.id.tvUpgradeInfo)
    TextView tvUpgradeInfo;
    @BindView(R.id.loadLibrary)
    Button mLoadLibrary;
    @BindView(R.id.cleanPatch)
    Button mCleanPatch;
    @BindView(R.id.killSelf)
    Button mKillSelf;
    @BindView(R.id.shp_file_self)
    Button mShpFileSelf;
    @BindView(R.id.showInfo)
    Button mShowInfo;
    @BindView(R.id.open_app)
    Button openApp;
    @BindView(R.id.btn_6)
    Button mBtn6;
    @BindView(R.id.simulation)
    Button mSimulation;
    @BindView(R.id.ce_test)
    Button mCeTest;
    @BindView(R.id.btn_7)
    Button mBtn7;
    @BindView(R.id.btn_8)
    Button mBtn8;
    @BindView(R.id.locationBtn)
    Button locationBtn;
    @BindView(R.id.version)
    TextView version;
    @BindView(R.id.input_txt)
    EditText inputTxt;
    @BindView(R.id.yunyinplay)
    Button yunyinplay;
    @BindView(R.id.clear_pwd)
    Button clearPwd;
    @BindView(R.id.aes_test)
    EditText aesTest;
    @BindView(R.id.aes_test_tv)
    TextView aesTestTv;
    @BindView(R.id.aes_jiami)
    Button aesJiami;
    @BindView(R.id.aes_jiemi)
    Button aesJiemi;
    @BindView(R.id.photography_construction)
    Button photographyConstruction;
    @BindView(R.id.bt_way_line)
    Button btWayLine;
    private List<String> mStringList;

    @SuppressLint("CheckResult")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        setContentView(R.layout.activity_home_);
        ButterKnife.bind(this);
        initdata();
        ThreadUtil.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                TextToSpeechUtils.getInstance(HomeActivity.this).initSpeak();
            }
        });
        version.setText("版本：" + UIUtils.getLocalVersionName());
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.INTERNET,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.SYSTEM_ALERT_WINDOW,
                Manifest.permission.READ_PHONE_STATE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {

                        }
                    }
                });
        //Loopview
        findViewById(R.id.btn_loopView).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                LoopViewActivity.show(HomeActivity.this);
            }
        });  findViewById(R.id.btn_record).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RecordServiceActivity.show(HomeActivity.this);
            }
        });
        //全景
        findViewById(R.id.btn_panorama).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PanoramaActivity.show(HomeActivity.this);
            }
        });

        findViewById(R.id.btn_gis).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GisMapActivity.show(HomeActivity.this);
            }
        });
        yunyinplay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtil.isEmpty(inputTxt.getText().toString())) {
                    return;
                }
                String s = inputTxt.getText().toString();
//                AmapTTSController.getInstance(HomeActivity.this).onSpeckTextToVice(s);
                TextToSpeechUtils.getInstance(HomeActivity.this).speak(s);
            }
        });

        photographyConstruction.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PolygonLineActivity.show(HomeActivity.this);
            }
        });
        btnLoadUpdateInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                loadUpgradeInfo();

            }
        });
        btWayLine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(HomeActivity.this, WayLineActivity.class));
            }
        });

        Button touchview = findViewById(R.id.touchview);
        touchview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                startActivity(new Intent(HomeActivity.this, PhotoEditorActivity.class));
//                startActivity(new Intent(HomeActivity.this, ShowPictureActivity.class));
                PictureInSampleActivity.show(HomeActivity.this);
            }
        });
        mLoadLibrary.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(HomeActivity.this, TestStatusBarActivity.class));
            }
        });
        mCleanPatch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(HomeActivity.this, MainXRichActivity.class));
            }
        });
        mKillSelf.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(HomeActivity.this, MainPictureActivity.class));
            }
        });

        mShpFileSelf.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(HomeActivity.this, SHPFileActivity.class));
            }
        });
        locationBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(HomeActivity.this, ADRegionalPromotionActivity.class));
            }
        });
        clearPwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SPManager.removeSP(LC.SP_DEFAULT_NAME);
                ToastUtils.showToast("清除成功");
                checkQuanxian();
            }
        });


        mShowInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setData(Uri.parse("pofly://com.lxzn.airservice/airservice?type=1&id=53"));
                // intent.putExtra("", "");//这里Intent当然也可传递参数,但是一般情况下都会放到上面的URL中进行传递
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });
        openApp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Intent intent = new Intent();
                    //
                    intent.setData(Uri.parse("pofly://com.lxzn.airservice/airservice?type=1&id=53"));
                    // intent.putExtra("", "");//这里Intent当然也可传递参数,但是一般情况下都会放到上面的URL中进行传递
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        switch (getXingqi()) {
            case 1:
                inputTxt.setText("今天星期日");
                break;
            case 2:
                inputTxt.setText("今天星期一");
                break;
            case 3:
                inputTxt.setText("今天星期二");
                break;
            case 4:
                inputTxt.setText("今天星期三");
                break;
            case 5:
                inputTxt.setText("今天星期四");
                break;
            case 6:
                inputTxt.setText("今天星期五");
                break;
            case 7:
                inputTxt.setText("今天星期六");
                break;
            default:
                break;
        }
        //SD路径
        LogUtil.e("路径 1", FileUtils.isSDCardAvailable() + "");
        LogUtil.e("路径 2", FileUtils.getExternalStoragePath() + "");
        File file = new File(FileUtils.getExternalStoragePath());
        createDirs(file);

        File[] files;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            files = getExternalFilesDirs(Environment.MEDIA_MOUNTED);
            for (File file2 : files) {
                LogUtil.e("路径 main", file2.getPath());
            }
        }

        aesJiami.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    /*
                     * 此处使用AES-128-ECB加密模式，key需要为16位。 128/8=16
                     */
                    String Key = "paiwujie20192019";//使用CFB加密，需要设置IV
                    String ddd = EncryptUtils.encrypt(aesTest.getText().toString(), Key);
                    LogUtil.e("加密解密 1", "加密：" + ddd);
                    aesTestTv.setText(ddd);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        aesJiemi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    String Key = "paiwujie20192019";//使用CFB加密，需要设置IV
                    String ddd = EncryptUtils.decrypt(aesTestTv.getText().toString(), Key);
                    LogUtil.e("加密解密 2", "解密：" + ddd);
                    aesTestTv.setText(ddd);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        String s = AESCipher.encrypt("07311233");
        LogUtil.e("加密解密 2", "解密：" + s);
        //df7872b901dfa703   c0590455acff07a4
        LogUtil.e("Main","AndroidID:"+getAndroidID(this));
        //获取无人机地址
        //114.262304,30.640121
        LocationAmpUtils.getInstance().getAddress(new LatLonPoint(30.640121, 114.262304), new LocationAmpUtils.RegeocodeSearchedListener() {
            @Override
            public void onRegeocodeSearched(String addressName) {
                LogUtil.e("高德地图", "onRegeocodeSearched：" + addressName);
            }
        });
    }

    /**
     * 获取设备AndroidID
     *
     * @param context 上下文
     * @return AndroidID
     */
    @SuppressLint("HardwareIds")
    public static String getAndroidID(Context context) {
        return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
    }
    /**
     * 创建文件夹
     */
    public static boolean createDirs(File file) {
        Log.e("路径 5", "filepath:" + file);
        if (!file.exists()) {
            return file.mkdirs();
        }
        return true;
    }

    public int getXingqi() {
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.DAY_OF_WEEK);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // checkQuanxian();
    }

    private void checkQuanxian() {
        String start_pwd = SPManager.getString(LC.SP_DEFAULT_NAME, "start_pwd", "000000");
        if (!checkPwd(start_pwd)) {
            showinputPwdDialog();
        } else {
            Beta.checkUpgrade();
        }
    }

    private void initdata() {
        mStringList = new ArrayList<>();
        mStringList.add("15974255013");
        mStringList.add("17363926973");
        mStringList.add("123456");
    }

    public void showinputPwdDialog() {
        IOSDialogUtils.getInstance().showEditDialogIos(this, false, new IOSDialogUtils.OnUploadDjiClickListener() {
            @Override
            public void onCancelButtonClick(IOSDialog dialog) {
                AppManager.getAppManager().AppExit(getApplicationContext());
            }

            @Override
            public void onPositiveButtonClick(IOSDialog dialog, EditText nikename) {
                if (checkPwd(nikename.getText())) {
                    dialog.dismiss();
                    ToastUtils.showToast("验证通过");
                    SPManager.saveString(LC.SP_DEFAULT_NAME, "start_pwd", nikename.getText().toString().trim());
                    Beta.checkUpgrade();
                } else {
                    ToastUtils.showToast("密码输入错误,请联系管理员！");
                }
            }
        });
    }


    public boolean checkPwd(CharSequence charSequence) {
        boolean isok = false;
        if (TextUtils.isEmpty(charSequence)) {
            ToastUtils.showToast("请输入密码");
            isok = false;
            return isok;
        }

        for (int i = 0; i < mStringList.size(); i++) {
            String pwd = mStringList.get(i);
            if (pwd.equals(charSequence.toString().trim())) {
                System.out.print("通过" + pwd);
                isok = true;
                break;
            }
        }
        return isok;
    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    @Override
    protected void onStop() {
        super.onStop();

    }


    /**
     * APp更新
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onAppUpdateEvent(AppUpdateEvent event) {

        AppUpdateService.getInstance().showDownloadAppView(this);
    }

    private void loadUpgradeInfo() {
        if (tvUpgradeInfo == null) {
            return;
        }
        /***** 获取升级信息 *****/
        UpgradeInfo upgradeInfo = Beta.getUpgradeInfo();

        if (upgradeInfo == null) {
            tvUpgradeInfo.setText("无升级信息");
            return;
        }
        StringBuilder info = new StringBuilder();
        info.append("id: ").append(upgradeInfo.id).append("\n");
        info.append("标题: ").append(upgradeInfo.title).append("\n");
        info.append("升级说明: ").append(upgradeInfo.newFeature).append("\n");
        info.append("versionCode: ").append(upgradeInfo.versionCode).append("\n");
        info.append("versionName: ").append(upgradeInfo.versionName).append("\n");
        info.append("发布时间: ").append(upgradeInfo.publishTime).append("\n");
        info.append("安装包Md5: ").append(upgradeInfo.apkMd5).append("\n");
        info.append("安装包下载地址: ").append(upgradeInfo.apkUrl).append("\n");
        info.append("安装包大小: ").append(upgradeInfo.fileSize).append("\n");
        info.append("弹窗间隔（ms）: ").append(upgradeInfo.popInterval).append("\n");
        info.append("弹窗次数: ").append(upgradeInfo.popTimes).append("\n");
        info.append("发布类型（0:测试 1:正式）: ").append(upgradeInfo.publishType).append("\n");
        info.append("弹窗类型（1:建议 2:强制 3:手工）: ").append(upgradeInfo.upgradeType);

        tvUpgradeInfo.setText(info);
    }

    @OnClick({R.id.btn_1, R.id.btn_2, R.id.btn_3,
            R.id.btn_4, R.id.btn_5, R.id.btn_6,
            R.id.btn_7, R.id.btn_8, R.id.btn_9,
            R.id.custom_knife,
            R.id.simulation, R.id.ce_test})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_1:
                startActivity(new Intent(HomeActivity.this, MapKmlActivity.class));
                break;
            case R.id.btn_2:
                startActivity(new Intent(HomeActivity.this, PlayMediaActivity.class));
                break;
            case R.id.btn_3:
                startActivity(new Intent(HomeActivity.this, CCBActivity.class));
                break;
            case R.id.btn_4:
                startActivity(new Intent(HomeActivity.this, CircleActivity.class));
                break;
            //地图操作
            case R.id.btn_5:
                startActivity(new Intent(HomeActivity.this, MapMainActivity.class));
                break;
            case R.id.btn_6:
                startActivity(new Intent(HomeActivity.this, CustViewActivity.class));
                break;
            case R.id.btn_7:
                startActivity(new Intent(HomeActivity.this, RenderGlActivity.class));
                break;
            case R.id.btn_8:
                startActivity(new Intent(HomeActivity.this, TaskTestActivity.class));
                break;
            case R.id.btn_9:
                startActivity(new Intent(HomeActivity.this, TextViewActivity.class));
                break;
            case R.id.custom_knife:
                startActivity(new Intent(HomeActivity.this, TextCustomKnifeActivity.class));
                break;
            case R.id.simulation:
                startActivity(new Intent(HomeActivity.this, MainClickActivity.class));
                break;
            case R.id.ce_test:
                Beta.checkUpgrade(true, false);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
